{extend name="base" /}
{block name="content"}
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li><a href="{:url('admin/dp/course')}">课程管理</a></li>
                <li class="layui-this">添加课程</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <form class="layui-form" action="{:url('admin/dp/save_course')}" method="post">
                        <div class="layui-form-item">
                            <label class="layui-form-label">课程名</label>
                            <div class="layui-input-block">
                                <input type="text" name="name" required lay-verify="required" placeholder="请输入课程名" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                          <label class="layui-form-label">课程模板</label>
                          <div class="layui-input-block">
                            <select name="template_id" id="template_id" lay-filter="template_id">
                              <option value="">请选择课程模板</option>
                              {foreach name="template_list" item="tpl"}
                              <option value="{$tpl.id}">{$tpl.name}</option>
                              {/foreach}
                            </select>
                          </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">课程分类</label>
                            <div class="layui-input-block">
                                <select name="category_id" lay-verify="required" >
                                    <option value="">请选择分类</option>
                                    {foreach name="category_list" item="cat"}
                                        <optgroup label="{$cat.name}">
                                            {foreach name="cat.children" item="sub"}
                                            <option value="{$sub.id}">{$sub.name}</option>
                                            {/foreach}
                                        </optgroup>
                                    {/foreach}
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                          <label class="layui-form-label">课程专家</label>
                          <div class="layui-input-block">
                            {foreach name="expert_list" item="expert"}
                            <input type="checkbox" name="expert_ids[]" title="{$expert.name}" value="{$expert.id}">
                            {/foreach}
                          </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上课时间</label>
                            <div class="layui-input-block">
                                <input type="text" name="course_time" id="course_time" required lay-verify="required" placeholder="请选择上课时间" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上课地点</label>
                            <div class="layui-input-block">
                                <input type="text" name="location" required lay-verify="required" placeholder="请输入上课地点" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">最大人数</label>
                            <div class="layui-input-block">
                                <input type="number" name="max_number" required lay-verify="required|number" placeholder="请输入最大预约人数" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">标题图片</label>
                            <div class="layui-input-inline">
                                <input type="text" name="title_image" id="title_image" placeholder="请上传标题图片" class="layui-input">
                                <img id="preview_title" src="" style="margin-top:10px;max-height:100px;display:none;">
                            </div>
                            <button type="button" class="layui-btn" id="upload_title_image">上传图片</button>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">海报图片</label>
                            <div class="layui-input-inline">
                                <input type="text" name="poster_image" id="poster_image" placeholder="请上传海报图片" class="layui-input">
                                <img id="preview_poster" src="" style="margin-top:10px;max-height:100px;display:none;">
                            </div>
                            <button type="button" class="layui-btn" id="upload_poster_image">上传图片</button>
                        </div>
                        

                        <div class="layui-form-item">
                            <label class="layui-form-label">课程介绍</label>
                            <div class="layui-input-block">
                                <textarea name="desc" placeholder="请输入课程介绍" class="layui-textarea"></textarea>
                            </div>
                        </div>
                       <div class="layui-form-item">
                            <label class="layui-form-label">课程回看</label>
                            <div class="layui-input-inline">
                                <input type="text" name="video_url" id="video_url" placeholder="请上传课程回看视频" class="layui-input">
                                <video id="preview_video" controls style="margin-top:10px;max-height:200px;display:none;"></video>
                                <div class="layui-progress" lay-filter="videoProgress" style="margin-top:10px;display:none;width: 280px;">
                                    <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
                                </div>
                            </div>
                            <button type="button" class="layui-btn" id="upload_video">上传视频</button>
                        </div>
                                    <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="submitCourse">提交</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="js"}
<script>
    layui.use(['form', 'laydate', 'upload'], function(){
        var form = layui.form, laydate = layui.laydate, upload = layui.upload;

        // 时间选择器
        laydate.render({
            elem: '#course_time',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss'
        });

form.on('select(template_id)', function(data){
 const templateId = data.value;
  console.log(templateId)
  if (!templateId) return;

  $.getJSON('/admin/dp/getTemplateInfo', { id: templateId }, function (res) {
    if (res.code === 1) {
      const tpl = res.data;
      $('input[name=name]').val(tpl.name);
      $('textarea[name=desc]').val(tpl.desc);
      $('input[name=location]').val(tpl.location);
      $('input[name=max_number]').val(tpl.max_number);
      $('input[name=title_image]').val(tpl.title_image);
      $('input[name=poster_image]').val(tpl.poster_image);
      $('#preview_title').attr('src', tpl.title_image).show();
      $('#preview_poster').attr('src', tpl.poster_image).show();
      $('select[name=category_id]').val(tpl.category_id);
      $('select[name=expert_id]').val(tpl.expert_id);
      form.render('select'); // 重新渲染 select
          // 👉 自动勾选专家 checkbox
      $('input[name="expert_ids[]"]').prop('checked', false);

// 再勾选对应专家
if (Array.isArray(tpl.expert_ids)) {
  tpl.expert_ids.forEach(function(id){
    $('input[name="expert_ids[]"][value="' + id + '"]').prop('checked', true);
  });
  form.render('checkbox'); // 重新渲染
}

  
    }
  });
});
        // 标题图片上传
        upload.render({
    elem: '#upload_title_image',
    url: '/index/index/upload',
    field: 'file',
    done: function(res){
        if(res.code === 1){
            const url = '/public/' + res.data.url;
            $('#title_image').val(url);
            $('#preview_title').attr('src', url).show();
            layer.msg('上传成功');
        } else {
            layer.msg('上传失败');
        }
    }
});
$('#upload_video').on('click', function () {
    const input = $('<input type="file" accept="video/*" style="display:none;">');
    $('body').append(input);
    input.click();
    input.on('change', function () {
        const file = this.files[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('file', file);

        const xhr = new XMLHttpRequest();
        const loadIndex = layer.load(1, { shade: 0.3 }); // 🔄 显示加载中

        xhr.open('POST', '/index/index/upload', true);

        xhr.onload = function () {
            layer.close(loadIndex); // ✅ 关闭 loading
            const res = JSON.parse(xhr.responseText);
            if (res.code === 1) {
                const url = '/public/' + res.data.url;
                $('#video_url').val(url);
                $('#preview_video').attr('src', url).show();
                layer.msg('上传成功');
            } else {
                layer.msg('上传失败');
            }
        };

        xhr.onerror = function () {
            layer.close(loadIndex); // ❌ 出错也关闭
            layer.msg('上传异常');
        };

        xhr.send(formData);
    });
});
// 海报图片上传 + 预览
upload.render({
    elem: '#upload_poster_image',
    url: '/index/index/upload',
    field: 'file',
    done: function(res){
        if(res.code === 1){
            const url = '/public/' + res.data.url;
            $('#poster_image').val(url);
            $('#preview_poster').attr('src', url).show();
            layer.msg('上传成功');
        } else {
            layer.msg('上传失败');
        }
    }
});


        // 提交表单
        form.on('submit(submitCourse)', function(data){
            $.ajax({
                url: data.form.action,
                type: data.form.method,
                data: $(data.form).serialize(),
                success: function(info){
                    if(info.code === 1){
                        setTimeout(function(){
                            window.location.href = "{:url('admin/dp/course')}";
                        }, 1000);
                    }
                    layer.msg(info.msg);
                }
            });
            return false;
        });
    });
</script>  
{/block}